package com.zhang.webadmin.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhang.webadmin.pojo.AclUserLoginToken;
import com.zhang.webadmin.service.AclUserLoginTokenService;
import com.zhang.webadmin.util.R;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private AclUserLoginTokenService aclUserLoginTokenService;
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 删除token
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (token != null) {
            aclUserLoginTokenService.remove(new LambdaQueryWrapper<>(AclUserLoginToken.class).eq(AclUserLoginToken::getToken, token));
        }
        
        response.getWriter().write(objectMapper.writeValueAsString(R.ok()));
    }
}
